package cn.sundat.service;

import java.util.List;

import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import cn.sundat.dao.CategoryDao;
import cn.sundat.model.Category;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

@Transactional
public class CategoryServiceImpl implements CategoryService {

	@Resource(name="categoryDao")
	private CategoryDao categoryDao;
	
	public List<Category> findCategoryAll() {
		//1 创建缓存管理器
		CacheManager cm = CacheManager.create(CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml"));
		//2 获取指定的缓存
		Cache cache = cm.getCache("categoryCache");
		//3 通过缓存获取数据，数据类似于map
		Element element = cache.get("clist");
		
		List<Category> list = null;
		if(element==null) {
			//从数据库中获取
			list = categoryDao.findCategoryAll();
			//将数据写入缓存
			cache.put(new Element("clist", list));
			System.out.println("从数据库中读取");
		}else {
			//从缓存中获取
			list = (List<Category>) element.getObjectValue();
			System.out.println("从缓存中读取的");
		}
		return list;
	}
	
	public List<Category> findCategoryByCode() {
		return categoryDao.findCategoryByCode();
	}

	
}
